//
//  LoginViewController.m
//  QuickCure
//
//  Created by haoge on 16/9/10.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "LoginViewController.h"
#import "NetWorkTool.h"
#import "HomeViewController.h"
#import "LeftViewController.h"
#import <SVProgressHUD.h>

@interface LoginViewController ()

@property (nonatomic,weak) UITextField *userNameTextField;

@property (nonatomic,weak) UITextField *passWordTextField;

@property (nonatomic,strong) NSNotification *notification;

//判断是否登录
@property (nonatomic,assign) BOOL isLogin;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"username"] || [[NSUserDefaults standardUserDefaults] valueForKey:@"password"])
    {
        self.userNameTextField.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"username"];
        
        self.passWordTextField.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"password"];
    }
}

- (void)setupUI
{
    self.title = @"登录";
    
#pragma mark -- 键盘弹出的通知
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    
    //设置登录界面图标的大图
    UIImageView *bigImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"product_img_logo_nor.png"]];
    
    [self.view addSubview:bigImageView];
    
    [bigImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50);
        make.height.equalTo(@100);
        make.width.equalTo(@75);
        make.centerX.equalTo(self.view);
    }];
    
    //设置登录界面图标的小图
    UIImageView *smallImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"product_text_logo_nor.png"]];
    
    [self.view addSubview:smallImageView];
    
    [smallImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bigImageView.mas_bottom);
        make.height.equalTo(@50);
        make.width.equalTo(@75);
        make.centerX.equalTo(self.view);
    }];
    
    //用户名输入框
    UITextField *userNameTextField = [[UITextField alloc] init];

    self.userNameTextField= userNameTextField;
    
    userNameTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    userNameTextField.placeholder = @"请输入用户名";
    
    [self.view addSubview:userNameTextField];
    
    [userNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(smallImageView.mas_bottom).offset(30);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@35);
    }];
    
    //密码输入框
    UITextField *passWordTextField = [[UITextField alloc] init];
    
    self.passWordTextField = passWordTextField;
    
    passWordTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    passWordTextField.placeholder = @"请输入密码";
    
    [self.view addSubview:passWordTextField];
    
    [passWordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userNameTextField.mas_bottom).offset(30);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@35);
    }];
    
    //登录按钮
    UIButton *loginBtn = [[UIButton alloc] init];
    
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"nav"] forState:UIControlStateNormal];
    
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    
    [loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:loginBtn];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passWordTextField.mas_bottom).offset(30);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.equalTo(@40);
    }];
    
}

- (void)loginBtnClick
{
    if ([self.userNameTextField.text isEqualToString:@"14"] && [self.passWordTextField.text isEqualToString:@"14"])
    {
        NSString *UrlString = kLoginUrl;
        
        NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f"};
        
        [[NetWorkTool shareManager] POST_RequestWithUrlString:UrlString parmas:paramDic successBloock:^(id responseObject) {
            
            self.isLogin = YES;
            
            [[NSUserDefaults standardUserDefaults] setValue:@"14" forKey:@"username"];
            
            [[NSUserDefaults standardUserDefaults] setValue:@"14" forKey:@"password"];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
//            NSLog(@"%@",responseObject);
            
            //取到根控制器
            JASidePanelController *rootVC = (JASidePanelController *)[UIApplication sharedApplication].keyWindow.rootViewController;
            
            //根据根控制器取到左侧控制器
            LeftViewController *leftVC = (LeftViewController *)rootVC.leftPanel;
            
            //设置为登录状态
            leftVC.isLogin = self.isLogin;
            
            //调用SVProgressHUD显示提示框
            
            [SVProgressHUD showSuccessWithStatus:@"登陆成功"];
            
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            
            [SVProgressHUD setFadeInAnimationDuration:0.5];
            
            [SVProgressHUD setFadeOutAnimationDuration:0.5];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
            [self.navigationController popViewControllerAnimated:NO];
            
        } failureBlock:^(NSError *error) {
            
            
            
        }];
    }
    
    else if ([self.userNameTextField.text isEqualToString:@""] || [self.passWordTextField.text isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"请填写完整的用户名或密码"];
        
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        
        [SVProgressHUD setFadeInAnimationDuration:0.5];
        
        [SVProgressHUD setFadeOutAnimationDuration:0.5];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
    
    else
    {
        [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
        
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        
        [SVProgressHUD setFadeInAnimationDuration:0.5];
        
        [SVProgressHUD setFadeOutAnimationDuration:0.5];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    
    if (self.view.frame.origin.y != 0)
    {
        [UIView animateWithDuration:0.25 animations:^{
            self.view.transform = CGAffineTransformIdentity;
        }];
    }
}

#pragma mark -- 键盘弹出更改frame

- (void)changeKeyboard:(NSNotification *)notification
{
//    NSLog(@"%@",notification);
    
    self.notification = notification;
    
    //1. 计算要移动的坐标
    
    //1.1 从通知中获取userInfo额外信息
    NSDictionary *userInfo = notification.userInfo;
    
    //1.2 获取开始的frame
//    CGRect beginFrame = [userInfo[@"UIKeyboardFrameBeginUserInfoKey"] CGRectValue];
    
    //1.3 获取结束的frame
    CGRect endFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    
    
    //1.4 计算要移动的距离
    //    CGFloat move = endFrame.origin.y - beginFrame.origin.y;
    CGFloat move = endFrame.origin.y - self.view.bounds.size.height;
    
    
    //2. 让界面跟着移动
    self.view.transform = CGAffineTransformMakeTranslation(0, move);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
